-- ========================================================
-- @File	: session.lua
-- @Brief	: 服务器会话数据
-- @Author	: Leo Zhao
-- @Date	: 2016-05-05
-- ========================================================
session = session or {}

-- 开始会话
function session.start()
	local sid = session.id();
	session.data = deserialize(store.get(sid) or "{}");
end

-- 取得当前的SessionId
function session.id()
	if session.cid then return session.cid end;
	session.cid = cookie.get('session_id');

	if not session.cid then
		session.cid = uuid();
		cookie.set('session_id', session.cid, store.expire(), '/');
	end

	return session.cid;
end

-- 取值
function session.get(key)
	return session.data[key];
end

-- 设置值
function session.set(key, value)
	if session.data[key] ~= value then
		session.modified = true;
		session.data[key] = value;
	end
end

-- 保存
function session.save()
	if session.modified then
		store.set(session.id(), serialize(session.data or {}));
		session.modified = false;
	end
end

-- 清空
function session.clear()
	session.data = {};
	session.modified = true;
end
